package imaa.escola.aluno.repository;

import imaa.escola.aluno.datatransfer.PesquisaAlunoDto;
import imaa.escola.aluno.domain.Aluno;
import imaa.framework.persistence.CustomRepository;

import java.util.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

public class AlunoRepositoryImpl implements CustomRepository<Aluno, PesquisaAlunoDto> {
	
	@Autowired
	private AlunoRepository repository;
	
	@Autowired
	private JdbcTemplate template;

	@SuppressWarnings("rawtypes")
	public List<Aluno> findByExample(PesquisaAlunoDto dto) {
		String sql = "SELECT * FROM aluno a, pessoa p WHERE 1=1 ";
		if (dto.nome != null) 
			sql += "AND LOWER(p.nome) LIKE LOWER('%" + dto.nome + "%') ";
		if (dto.cpf != null)
			sql += "AND cpf = " + dto.cpf + " ";
		
		sql += "AND a.SEQ_PESSOA = p.SEQ_PESSOA";
		
		List<Aluno> lista = new ArrayList<Aluno>();
		List<Map<String,Object>> rows = template.queryForList(sql);
		
		for (Map row : rows) {
			Aluno aluno = new Aluno();
			aluno.setId(Long.parseLong(String.valueOf(row.get("SEQ_PESSOA"))));
			aluno.setNome((String)(row.get("NOME")));
			aluno.setCep((String)(row.get("CEP")));
			aluno.setCpf((String)(row.get("CPF")));
			
			Calendar dtNasc = Calendar.getInstance();
			dtNasc.setTime(new Date());
			//aluno.setDataNascimento(Calendar.getInstance().setTime((Date)(row.get("DT_NASCIMENTO"))));
			
			lista.add(aluno);
		}
		return lista;
	}

}
